package com.mhy.soloader;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    public static final String APP_SO = "so";
//    static {
//        //静态加载so
//        System.loadLibrary("native-lib");
//    }

    public native String stringFromJNI();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 一次请求多个权限[], 如果其他有权限是已经授予的将会自动忽略掉
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
            }
        }
        TextView tv = findViewById(R.id.sample_text);

        loadSo("libnative-lib.so");//外部加载so
        // JNI 调用
        tv.setText(stringFromJNI());

/*******AssetsSo方案*******/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String serial = Register.regSerial("12-34-567", true);
                serial = serial.replace("-", "").toLowerCase();
                tv.setText(serial);
            }
        }, 2000);
/*********AssetsSo*********/
    }


    public  void loadSo(String soName){
        String dir = this.getDir(APP_SO, MODE_PRIVATE).getAbsolutePath();
        File distFile = new File(dir + File.separator + soName);
        if (copyFileFromAssets(this, soName, distFile.getAbsolutePath())) {
            //使用load方法加载内部储存的SO库
            System.load(distFile.getAbsolutePath());
            // 接下来执行native放法吧
        }
    }

    /**
     * assets文件->data/data/xx/app_so/
     */
    public static boolean copyFileFromAssets(Context context, String fileName, String path) {
        boolean copyIsFinish = false;
        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("MainActivity", "[copyFileFromAssets] IOException " + e.toString());
        }
        return copyIsFinish;
    }


}